package com.zy.mc_module.base.kotlin

import android.content.Context
import com.zy.mc_module.mvp.base.IView
import com.zy.mc_module.mvp.base.IPresenter
import android.view.View.OnTouchListener
import com.kingja.loadsir.core.LoadService
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import androidx.recyclerview.widget.RecyclerView
import android.content.Intent
import com.zy.mc_module.R
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.hwangjr.rxbus.RxBus
import com.kingja.loadsir.core.LoadSir
import com.kingja.loadsir.callback.Callback.OnReloadListener
import android.view.MotionEvent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.kingja.loadsir.callback.Callback
import com.zy.mc_module.base.BaseAdapter
import com.zy.mc_module.utils.StringsUtils
import com.zy.mc_module.utils.AppTools
import com.zy.mc_module.utils.loadsir.LoadingCallback
import com.zy.mc_module.utils.loadsir.EmptyCallback
import com.zy.mc_module.utils.FixMemLeak
import com.zy.mc_module.utils.loadsir.ErrorCallback
import java.util.*

/**
 * Created on 18/10/20
 * Fragment基类
 */
abstract class BaseFragment<V : IView, P : IPresenter<V>, VB : ViewBinding> : Fragment(), OnTouchListener {
    var TAG = javaClass.simpleName + ""
    protected var presenter: P? = null
    lateinit var mContext: Context
    lateinit var binding: VB

    //Fragment View
    private var convertView: View? = null
    lateinit var loadService: LoadService<*>

    //是否使用LoadSir
    private var isNeedLoadSir = false

    //指定需要加载的视图,-1代表未指定
    private var loadViewid = -1

    //视图是否加载完毕
    private var isViewPrepare = false

    //数据是否加载过了
    protected var hasLoadData = false

    //下拉刷新
    private var refreshLayout: SmartRefreshLayout? = null
    private var recyclerView: RecyclerView? = null

    /**
     * 分页加载
     */
    protected var page = 1 //页数
    protected var size = 10 //每页数目

    /***
     * 布局文件Id
     */
    abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB

    override fun startActivity(intent: Intent) {
        super.startActivity(intent)
        if (null != activity) requireActivity().overridePendingTransition(
            R.anim.activity_in_from_right,
            R.anim.activity_out_from_left
        )
    }

    /***
     * 绑定Activity
     */
    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        presenter = createPresenter()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (convertView == null) {
            binding = getViewBinding(inflater,container)
            convertView = binding.root
        }
        //是否使用RxBus
        if (isNeedRxBus) {
            RxBus.get().register(this)
        }
        //判断LoadSir
        isLoadSir()
        //是否使用LoadSir
        return if (isNeedLoadSir) {
            //判断 是否指定了需要加载的视图
            loadService = LoadSir.getDefault().register(
                if (-1 == loadViewid) convertView else convertView!!.findViewById(loadViewid),
                OnReloadListener { v: View? -> reloadData() })

            // return loadService.getLoadLayout();
            // return convertView;
            if (-1 == loadViewid) loadService.getLoadLayout() else convertView
        } else {
            convertView
        }
    }

    /***
     * onCreateView执行完毕后调用
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.setOnTouchListener(this)
        if (null != presenter) {
            //绑定Activity
            presenter!!.attachView(this as V)
        }
        //初始化视图
        initView(savedInstanceState)
        // TODO: 18/12/17  可以将初始化事件放到 懒加载那里 应该可以避免 RecyclerView 的Adapter点击事件为空 
        //初始化事件
        initListener()
    }

    override fun onTouch(v: View, event: MotionEvent): Boolean {
        return true //消费掉点击事件,防止跑到下一层去
    }

    /***
     * Fragment创建完
     */
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //视图加载完了
        isViewPrepare = true
        //懒加载
        LazyLoadData()
    }

    /***
     * Fragment UI是否可见
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            //UI可见进行懒加载
            LazyLoadData()
        }
    }

    /***
     * 懒加载Fragment数据
     */
    private fun LazyLoadData() {
        //临时添加的方法,数据加载过了的也可以再次加载
        if (userVisibleHint && isViewPrepare) {
            LoadData()
        }
        //只有在Fragment UI可见，视图已经加载完，并且没有加载过数据才能进行懒加载
        if (userVisibleHint && isViewPrepare && !hasLoadData) {
            //懒加载数据
            LazyLoad()
            hasLoadData = true
        }
    }

    /***
     * 创建Mvp Presenter实例
     */
    protected open fun createPresenter(): P? {
        return null
    }

    protected abstract fun initView(savedInstanceState: Bundle?)
    protected fun initListener() {}

    /***
     * 临时添加的方法,数据加载过了的也可以再次加载
     */
    protected fun LoadData() {}

    /***
     * 懒加载数据
     */
    protected abstract fun LazyLoad()

    /***
     * LoadSir的重新加载数据
     */
    protected open fun reloadData() {}

    /***
     * 是否使用RxBus
     */
    protected val isNeedRxBus: Boolean
        protected get() = false

    /***
     * 是否使用LoadSir等一系列功能
     * arg[0]:使用LoadSir
     * arg[1]:指定需要加载的视图
     */
    protected open fun isLoadSir(vararg objects: Any) {
        if (objects.size == 1) {
            //使用LoadSir,未指定加载视图
            isNeedLoadSir = objects[0] as Boolean
        } else if (objects.size == 2) {
            //使用LoadSir,并指定需要加载视图
            isNeedLoadSir = objects[0] as Boolean
            loadViewid = objects[1] as Int
        }
    }

    /***
     * 封装下拉刷新/上拉加载逻辑
     */
    protected fun initRefresh(refreshLayout: SmartRefreshLayout, recyclerView: RecyclerView?) {
        this.recyclerView = recyclerView
        this.refreshLayout = refreshLayout

        //下拉刷新
        refreshLayout.setOnRefreshListener { refreshlayout ->
            refreshlayout.setEnableLoadMore(true)
            page = 1
            refreshData(true)
        }
        //上拉加载
        refreshLayout.setOnLoadMoreListener {
            page++
            refreshData(false)
        }
    }

    /***
     * 刷新加载数据
     */
    protected open fun refreshData(ReOrLo: Boolean) {}

    /***
     * 刷新完成
     */
    protected fun <T> refreshComplete(any: Any?) {
        if (any is MutableList<*>) {
            val list: MutableList<T> = any as MutableList<T>
            val recyclerViewAdapter = recyclerView?.adapter
            if (null != recyclerViewAdapter) {
                if (recyclerViewAdapter is BaseAdapter<*>) {
                    val adapter = recyclerView?.adapter as BaseAdapter<T>?
                    if (page == 1) {
                        adapter!!.setAll(list)
                        if (adapter.list.size > 0) {
                            recyclerView!!.scrollToPosition(0)
                        }
                    } else {
                        adapter!!.addAll(list)
                    }
                }else if (recyclerViewAdapter is com.zy.mc_module.base.kotlin.BaseAdapter<*, *>) {
                    val adapter = recyclerView?.adapter as com.zy.mc_module.base.kotlin.BaseAdapter<*, T>?
                    if (page == 1) {
                        adapter!!.setAll(list)
                        if (adapter.getList().size > 0) {
                            recyclerView!!.scrollToPosition(0)
                        }
                    } else {
                        adapter!!.addAll(list)
                    }
                } else if (recyclerViewAdapter is BaseQuickAdapter<*, *>) {
                    val adapter = recyclerView!!.adapter as BaseQuickAdapter<T, *>?
                    if (page == 1) {
                        adapter!!.setNewData(list)
                        if (adapter.data.size > 0) {
                            recyclerView!!.scrollToPosition(0)
                        }
                    } else {
                        adapter?.addData(list)
                    }
                }
            }
            if (StringsUtils.isEmpty(list) && page > 1) {
                page--
                refreshLayout!!.setEnableLoadMore(false)
            }
        } else if (any is Boolean) {
            if (any && page > 1) {
                page--
            }
        }
        AppTools.finishRefresh(refreshLayout)
    }
    //--------------------------------LoadSir-----------------------------------
    /***
     * 显示加载页
     */
    fun showLoading() {
        if (null != loadService) {
            loadService!!.showCallback(LoadingCallback::class.java)
        }
    }

    /***
     * 关闭加载页
     */
    fun disLoading() {
        loadService!!.showSuccess()
    }

    /***
     * 请求错误页
     */
    fun showError() {
        loadService!!.showCallback(ErrorCallback::class.java)
    }

    fun showError(list: List<*>?) {
        if (null == list || list.size <= 0) {
            loadService!!.showCallback(ErrorCallback::class.java)
        } else {
            disLoading()
        }
    }

    /***
     * 暂无数据页
     */
    fun showEmpty() {
        loadService!!.showCallback(EmptyCallback::class.java)
    }

    /***
     * 暂无数据页
     */
    fun showEmpty(callback: Class<out Callback?>?) {
        loadService!!.showCallback(callback)
    }

    fun showEmpty(list: List<*>?) {
        if (null == list || list.size <= 0) {
            loadService!!.showCallback(EmptyCallback::class.java)
        } else {
            disLoading()
        }
    }

    fun showEmpty(list: List<*>?, callback: Class<out Callback?>?) {
        if (null == list || list.size <= 0) {
            loadService!!.showCallback(callback)
        } else {
            disLoading()
        }
    }

    fun LayoutInflater(layoutId: Int, view: ViewGroup?): View {
        return LayoutInflater.from(context).inflate(layoutId, view, false)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isNeedRxBus) {
            //注销RxBus
            RxBus.get().unregister(this)
        }
        if (null != presenter) {
            presenter!!.detachView()
            presenter = null
        }
        //取消订阅
        //SubscriptionManager.getInstance().cancelall();
        FixMemLeak.fixLeak(context)
    }
}